import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.await
import kotlinx.coroutines.launch
import org.w3c.fetch.CORS
import org.w3c.fetch.RequestInit
import org.w3c.fetch.RequestMode
import org.w3c.fetch.Response
import kotlin.js.Promise

external suspend fun fetch(input: dynamic, init: RequestInit = definedExternally): Promise<Response>

external val chrome: dynamic
fun main() {
  println("hello background")

  chrome.runtime.onMessage.addListener(::handler)
}

fun handler(message: String, sender: Any, sendResponse: (Any) -> Unit) {
  println("background received message: $message from $sender")
  CoroutineScope(Dispatchers.Default).launch {
    val text = fetch("https://www.baidu.com", RequestInit(mode = RequestMode.CORS)).await().text().await()
    println(text)
  }
}
